package com.iot.inclinometer.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.iot.inclinometer.R;
import com.iot.inclinometer.dao.IBaseInfoDao;
import com.iot.inclinometer.dao.ICorrectDataInfoDao;
import com.iot.inclinometer.dao.IDataInfoDao;
import com.iot.inclinometer.dao.ILeijiInfoDao;
import com.iot.inclinometer.dao.IObserveInfoDao;
import com.iot.inclinometer.dao.IRealInfoDao;
import com.iot.inclinometer.dao.impl.BaseInfoDaoImpl;
import com.iot.inclinometer.dao.impl.CorrectDataInfoDaoImpl;
import com.iot.inclinometer.dao.impl.DataInfoDaoImpl;
import com.iot.inclinometer.dao.impl.LeijiInfoDaoImpl;
import com.iot.inclinometer.dao.impl.ObserveInfoDaoImpl;
import com.iot.inclinometer.dao.impl.RealInfoDaoImpl;
import com.iot.inclinometer.pojo.BaseInfo;
import com.iot.inclinometer.pojo.CorrectDataInfo;
import com.iot.inclinometer.pojo.DataInfo;
import com.iot.inclinometer.pojo.LeijiInfo;
import com.iot.inclinometer.pojo.ObserveInfo;
import com.iot.inclinometer.pojo.RealInfo;
import com.iot.inclinometer.util.BaseUtil;
import com.iot.inclinometer.util.Common;
import com.iot.inclinometer.util.ContextApplication;
import com.iot.inclinometer.util.JXLCreate;
import com.iot.inclinometer.util.JXLCreateResult;
import com.iot.inclinometer.util.JXLExportAll;
import com.iot.inclinometer.util.JXLImportAll;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * “导出”页面
 *
 * @author ZSL
 *
 */
public class OutputProUI extends Activity{
	private TextView titleView;		//显示标题(产品型号)
	private ImageView newProBtn;
	private ImageView paintBtn;
	private ImageView oldProBtn;
	/** 上传 */
	private ImageView uploadDBBtn;
	private ImageView configurationBtn;
	private ImageView exitBtn;

	private String model=null;    //产品型号

	private int FILE_RESULT_CODE = 0;
	private int FILE_EXPORT_CODE = 0;
	private int FILE_IMPORT_CODE = 0;
	private final String MEASURE_ANGLE_0="A0方向";
	/**导出文件夹目录编辑框*/
	private EditText file_edit = null;
	/**选择导出文件夹按钮*/
	private Button selectFileBtn = null;
	/** 按全部公程导出 */
	private Button outputAllProjectBtn = null;
	/** 按工程名导出 */
	private Button outputByProjectNameBtn = null;
	/** 按工点名导出 */
	private Button outputByItemNameBtn = null;
	/** 按钻孔编号导出 */
	private Button outputByDrillNumBtn = null;

	/** 按钻孔编号导出三级联动下拉菜单中的一级菜单 */
	private Spinner projectNameSp = null;
	/** 按钻孔编号导出三级联动下拉菜单中的二级菜单 */
	private Spinner itemNameSp = null;
	/** 按钻孔编号导出三级联动下拉菜单中的三级菜单 */
	private Spinner drillNumSp = null;

	/**导出备份文件夹目录编辑框*/
	private EditText export_backup_edit= null;
	/**选择导出备份文件夹目录按钮*/
	private Button selExbackupfolderBtn= null;
	/**导出备份按钮*/
	private Button exportBackupBtn= null;

	/**导入备份文件目录编辑框*/
	private EditText import_backup_edit= null;
	/**选择导入备份文件目录按钮*/
	private Button selImbackupfileBtn= null;
	/**导入备份按钮*/
	private Button importBackupBtn = null;

	private ArrayAdapter<String> projectAdapter = null;

	private ArrayAdapter<String> itemAdapter = null;

	private ArrayAdapter<String> drillAdapter = null;

	private InputMethodManager inputMethodManager;       //控制键盘隐藏

	private IBaseInfoDao baseInfoDao = new BaseInfoDaoImpl(this);
	private IObserveInfoDao observeInfoDao = new ObserveInfoDaoImpl(this);
	private IDataInfoDao dataInfoDao = new DataInfoDaoImpl(this);
	private ILeijiInfoDao leijiInfoDao=new LeijiInfoDaoImpl(this);
	private ICorrectDataInfoDao correctDataInfoDao = new CorrectDataInfoDaoImpl(this);
	private IRealInfoDao realInfoDao = new RealInfoDaoImpl(this);
	//创建一个定长线程池，可控制线程最大并发数，超出的线程会在队列中等待
	private ExecutorService fixedThreadPool = Executors.newFixedThreadPool(4);


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.output_pro_activity);
		inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		SharedPreferences sharedPreferences= ContextApplication.getAppContext().getSharedPreferences("configuration",0);
		model=sharedPreferences.getString("Model","");
		initView();
		setBtnListener();
		initMenu();
	}
    /*
     * 初始化控件
     * */
	private void initView() {
		titleView=(TextView) findViewById(R.id.tv_top_title); 	//初始化标题
		String newTitle = Common.isEmpty(model)?"":"("+model+")";
		titleView.setText(titleView.getText()+ newTitle);

		oldProBtn = (ImageView) findViewById(R.id.old_pro_btn);
		paintBtn = (ImageView) findViewById(R.id.paint_btn);
		newProBtn = (ImageView) findViewById(R.id.new_pro_btn);
		uploadDBBtn = (ImageView) findViewById(R.id.uploaddbToServer_btn);
		configurationBtn = (ImageView) findViewById(R.id.configuration_btn);
		exitBtn = (ImageView) findViewById(R.id.exit_btn);
		// 初始化主界面中的按钮和输入控件
		//普通导出，文件夹目录
		file_edit = (EditText) findViewById(R.id.file_edit);
		if(getSharedPreferences("defaultFilePath",0).getString("Path","").equals(""))
		{
			SharedPreferences sharedPreferences=getSharedPreferences("defaultFilePath",0);
			sharedPreferences.edit()
				.putString("Path",getSDPath(OutputProUI.this)+ File.separator +"久感测斜")
				.commit();
			file_edit.setText(sharedPreferences.getString("Path",null));
		}else{
			SharedPreferences sharedPreferences=getSharedPreferences("defaultFilePath",0);
			file_edit.setText(sharedPreferences.getString("Path",null));
		}
		selectFileBtn=(Button)findViewById(R.id.select_file_btn);

		outputAllProjectBtn=(Button)findViewById(R.id.output_all_project_btn);
		outputByProjectNameBtn=(Button)findViewById(R.id.output_by_project_btn);
		outputByItemNameBtn=(Button)findViewById(R.id.output_by_item_btn);
		outputByDrillNumBtn = (Button) findViewById(R.id.output_by_drill_btn);

		projectNameSp = (Spinner) findViewById(R.id.project_name_spinner);
		itemNameSp = (Spinner) findViewById(R.id.item_name_spinner);
		drillNumSp = (Spinner) findViewById(R.id.drill_num_spinner);

		//导出备份，文件夹目录
		export_backup_edit= (EditText) findViewById(R.id.export_backup_edit);
		if(getSharedPreferences("defaultFilePath",0).getString("ExportBackupPath","").equals(""))
		{
			SharedPreferences sharedPreferences=getSharedPreferences("defaultFilePath",0);
			sharedPreferences.edit()
				.putString("ExportBackupPath",getSDPath(OutputProUI.this)+ File.separator +"久感测斜导出备份")
				.commit();
			export_backup_edit.setText(sharedPreferences.getString("ExportBackupPath",null));
		}else{
			SharedPreferences sharedPreferences=getSharedPreferences("defaultFilePath",0);
			export_backup_edit.setText(sharedPreferences.getString("ExportBackupPath",null));
		}
		selExbackupfolderBtn=(Button)findViewById(R.id.sel_exbackupfolder_btn);
		exportBackupBtn=(Button)findViewById(R.id.export_backup_btn);

		//导入备份，文件目录
		import_backup_edit=  (EditText) findViewById(R.id.import_backup_edit);
		selImbackupfileBtn=(Button)findViewById(R.id.sel_imbackupfile_btn);
		importBackupBtn=(Button)findViewById(R.id.import_backup_btn);
	}
    /*
     * 设置按钮的点击监听
     * */
	private void setBtnListener() {
		oldProBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(OutputProUI.this, OldProUI.class);
				startActivity(intent);
				OutputProUI.this.finish();
			}
		});
		paintBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(OutputProUI.this, PaintProUI.class);
				startActivity(intent);
				OutputProUI.this.finish();
			}
		});
		newProBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(OutputProUI.this, NewProUI.class);
				startActivity(intent);
				OutputProUI.this.finish();
			}
		});
		uploadDBBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(OutputProUI.this, UploadDBToServerUI.class);
				startActivity(intent);
				OutputProUI.this.finish();
			}
		});
		configurationBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(OutputProUI.this, ConfigurationLicenseUI.class);
				startActivity(intent);
			}
		});
		exitBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				sureDialog();
			}
		});
		projectNameSp.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				try {
					outputAllProjectBtn.setEnabled(true);
					outputByProjectNameBtn.setEnabled(true);
					outputByItemNameBtn.setEnabled(true);
					outputByDrillNumBtn.setEnabled(true);
					initMenu2();
					initMenu3();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}
		});
		itemNameSp.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				try {
					outputByItemNameBtn.setEnabled(true);
					outputByDrillNumBtn.setEnabled(true);
					initMenu3();
				} catch (Exception exception) {
					exception.printStackTrace();
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}
		});
		drillNumSp.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				try {
					outputByDrillNumBtn.setEnabled(true);
				} catch (Exception exception) {
					exception.printStackTrace();
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}
		});
		selectFileBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(OutputProUI.this,MyFileManager.class);
				FILE_RESULT_CODE=1;
				startActivityForResult(intent,FILE_RESULT_CODE);
			}
		});
		//选择导出备份文件夹目录
		selExbackupfolderBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(OutputProUI.this,MyFileManager.class);
				FILE_EXPORT_CODE=1;
				startActivityForResult(intent,FILE_EXPORT_CODE);
			}
		});
		//选择导入备份文件目录
		selImbackupfileBtn.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				Intent intent = new Intent(OutputProUI.this,MyXlsManager.class);
				FILE_IMPORT_CODE=1;
				startActivityForResult(intent,FILE_IMPORT_CODE);
			}
		});
		file_edit.addTextChangedListener(new TextWatcher() {
			//监听文件夹路径变化，有变化时，使四个导出按钮可用
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}
			@Override
			public void afterTextChanged(Editable s) {
				outputAllProjectBtn.setEnabled(true);
				outputByProjectNameBtn.setEnabled(true);
				outputByItemNameBtn.setEnabled(true);
				outputByDrillNumBtn.setEnabled(true);
			}
		});
		export_backup_edit.addTextChangedListener(new TextWatcher() {
			//监听导出备份文件夹路径变化，有变化时，使导出备份按钮可用
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}
			@Override
			public void afterTextChanged(Editable s) {
				exportBackupBtn.setEnabled(true);
			}
		});
		import_backup_edit.addTextChangedListener(new TextWatcher() {
			//监听导入备份文件路径变化，有变化时，使导入备份按钮可用
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}
			@Override
			public void afterTextChanged(Editable s) {
				importBackupBtn.setEnabled(true);
			}
		});
		//导出按钮的事件监听
		outputAllProjectBtn.setOnClickListener(outputAllProjectClickListener);
		outputByProjectNameBtn.setOnClickListener(outputByProjectNameClickListener);
		outputByItemNameBtn.setOnClickListener(outputByItemNameClickListener);
		outputByDrillNumBtn.setOnClickListener(outputByDrillClickListener);
		exportBackupBtn.setOnClickListener(exportBackupClickListener);
		importBackupBtn.setOnClickListener(importBackupClickListener);
	}

	/**
	 * 按全部工程导出数据
	 */
	private OnClickListener outputAllProjectClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			String filePath = file_edit.getText().toString().trim();
			List<BaseInfo> all = baseInfoDao.selectBaseInfos();
			int flag1=0,flag2=0;           //标志flag1==0全部为空，flag2==1部分为空
			Long start = System.currentTimeMillis();

			if(BaseUtil.isEmpty(filePath,OutputProUI.this)){
				for (BaseInfo baseInfo : all) {
					ObserveInfo observeInfo0 = new ObserveInfo();/***检验上一次的观测信息是否有对应的修正信息**/
						List<ObserveInfo> alls1= new ArrayList<ObserveInfo>();//
					alls1= observeInfoDao.selectObserverInfos(baseInfo.getBaseId(),
							MEASURE_ANGLE_0);
					// 判断取出的记录是否为空
					if (alls1.size() < 1) {
						observeInfo0.setCount(1);
					} else {//
					int max1= 1;
					for (ObserveInfo observeInfo3 : alls1) {
						int i = observeInfo3.getCount();
						if (i > max1){
							max1= i;
						}
					 }

					ObserveInfo observeInfo1=observeInfoDao.selectObserveInfo(MEASURE_ANGLE_0,baseInfo.getBaseId(),max1);
					int obId=observeInfo1.getObserveId();
					int obId1=obId+1;
					List<CorrectDataInfo> correctDataInfos=correctDataInfoDao.selectDataInfos(obId);
					if (correctDataInfos.size()<=0) {
						observeInfoDao.deleteObserveInfoByobId(obId);
						observeInfoDao.deleteObserveInfoByobId(obId1);
						}else{


						}
			     }
					List<ObserveInfo> observeInfos = observeInfoDao
							.selectObserverInfos(baseInfo.getBaseId());
					if (observeInfos.size() < 1) {
						flag2=1;
					} else {
						//导出A0和A180方向观测的修正数据，一个文件
						flag1=1;
						for (ObserveInfo observeInfo : observeInfos) {
							//只根据A0方向的ob_id导出相应修正数据的文件，A180方向的观测信息无用
							//导出功能中，只导出A0，A180两个方向数据计算后的主滑、非主滑、合成滑动位移
							if(observeInfo.getMeasurecount().equals(MEASURE_ANGLE_0)){
								List<CorrectDataInfo> correctDataInfoList = correctDataInfoDao.
										selectDataInfos(observeInfo.getObserveId());
								if(observeInfo.getCount()==1){
									//如果是第一次观测，且有修正观测数据，设置三种位移值都为0
									if(correctDataInfoList.size()>0){
										for(CorrectDataInfo correctDataInfo:correctDataInfoList){
											correctDataInfo.setLx("0");
											correctDataInfo.setLy("0");
											correctDataInfo.setError("0");
										}
									}
								}

								JXLCreate jxCreate = new JXLCreate(filePath,baseInfo,observeInfo,correctDataInfoList,OutputProUI.this);
								fixedThreadPool.execute(jxCreate);
							}
						}

						//导出多次观测的修正数据
						List<ObserveInfo> observeInfosA0 = observeInfoDao
								.selectObserverInfos(baseInfo.getBaseId(),MEASURE_ANGLE_0);

						List<List<CorrectDataInfo>> correctDataInfoLists =new ArrayList<List<CorrectDataInfo>>();

						//取出每一次观测的修正数据List
						for(ObserveInfo observeInfo:observeInfosA0){
							List<CorrectDataInfo> correctDataInfos=new ArrayList<CorrectDataInfo>();
							correctDataInfos=correctDataInfoDao.selectDataInfos(observeInfo.getObserveId());
							correctDataInfoLists.add(correctDataInfos);
						}

						JXLCreateResult jxCreateResult = new JXLCreateResult(filePath,baseInfo,observeInfosA0,
								correctDataInfoLists,OutputProUI.this);
						fixedThreadPool.execute(jxCreateResult);

						SharedPreferences sharedPreferences=getSharedPreferences("defaultFilePath",0);
						sharedPreferences.edit().putString("Path", filePath).commit();
					}
				}
				Long end = System.currentTimeMillis();
				Log.i("info", "时间-->"+(end-start));
				if(flag1==0){
					showMsg("导出失败！全部工程中的全部孔都没有数据！");
				}else{
					outputAllProjectBtn.setEnabled(false);
					if(flag2==1){
						showMsg("导出成功！但全部工程中存在没有数据的孔！");
					}
					else{
						showMsg("导出成功！");
					}
				}
			}else
			{	// 弹出吐司，表示导出失败
				Toast.makeText(OutputProUI.this, "导出失败！",
						Toast.LENGTH_LONG).show();
			}
		}
	};


	/**
	 * 导出一个项目中的所有数据
	 */
	private OnClickListener outputByProjectNameClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			String filePath = file_edit.getText().toString().trim();
			if(projectNameSp.getSelectedItem()==null){
				showMsg("工程为空，导出失败！");
			}else{
			String _projectName=projectNameSp.getSelectedItem()
					.toString();
			List<BaseInfo> all = baseInfoDao.selectBaseInfos(_projectName);
			int flag1=0,flag2=0;           //标志flag1==0全部为空，flag2==1部分为空
			if(BaseUtil.isEmpty(filePath,OutputProUI.this)){
				for (BaseInfo baseInfo : all) {
					ObserveInfo observeInfo0 = new ObserveInfo();/***检验上一次的观测信息是否有对应的修正信息**/
					List<ObserveInfo> alls1= new ArrayList<ObserveInfo>();
				alls1= observeInfoDao.selectObserverInfos(baseInfo.getBaseId(),
						MEASURE_ANGLE_0);
				// 判断取出的记录是否为空
				if (alls1.size() < 1) {
					observeInfo0.setCount(1);
				} else {//
				int max1= 1;
				for (ObserveInfo observeInfo3 : alls1) {
					int i = observeInfo3.getCount();
					if (i > max1){
						max1= i;
					}
				 }

				ObserveInfo observeInfo1=observeInfoDao.selectObserveInfo(MEASURE_ANGLE_0,baseInfo.getBaseId(),max1);
				int obId=observeInfo1.getObserveId();
				int obId1=obId+1;
				List<CorrectDataInfo> correctDataInfos=correctDataInfoDao.selectDataInfos(obId);
				if (correctDataInfos.size()<=0) {
					observeInfoDao.deleteObserveInfoByobId(obId);
					observeInfoDao.deleteObserveInfoByobId(obId1);
					}else{


					}
		     }//*///
					List<ObserveInfo> observeInfos = observeInfoDao
							.selectObserverInfos(baseInfo.getBaseId());
					if (observeInfos.size() < 1) {
						flag2=1;
					} else {
						//导出单次观测的观测数据和修正数据
						flag1=1;
						for (ObserveInfo observeInfo : observeInfos) {
							//只根据A0方向的ob_id导出相应修正数据的文件，A180方向的观测信息无用
							//导出功能中，只导出A0，A180两个方向数据计算后的主滑、非主滑、合成滑动位移
							if(observeInfo.getMeasurecount().equals(MEASURE_ANGLE_0)){
								List<CorrectDataInfo> correctDataInfoList = correctDataInfoDao.
										selectDataInfos(observeInfo.getObserveId());
								if(observeInfo.getCount()==1){
									//如果是第一次观测，且有修正观测数据，设置三种位移值都为0
									if(correctDataInfoList.size()>0){
										for(CorrectDataInfo correctDataInfo:correctDataInfoList){
											correctDataInfo.setLx("0");
											correctDataInfo.setLy("0");
											correctDataInfo.setError("0");
										}
									}
								}
								JXLCreate jxCreate = new JXLCreate(filePath,baseInfo,observeInfo,correctDataInfoList,OutputProUI.this);
								new Thread(jxCreate).start();
							}
						}
						//导出多次观测的修正数据
						List<ObserveInfo> observeInfosA0 = observeInfoDao
								.selectObserverInfos(baseInfo.getBaseId(),MEASURE_ANGLE_0);
						List<List<CorrectDataInfo>> correctDataInfoLists =new ArrayList<List<CorrectDataInfo>>();
						//取出每一次观测的修正数据List
						for(ObserveInfo observeInfo:observeInfosA0){
							List<CorrectDataInfo> correctDataInfos=new ArrayList<CorrectDataInfo>();
							correctDataInfos=correctDataInfoDao.selectDataInfos(observeInfo.getObserveId());
							correctDataInfoLists.add(correctDataInfos);
						}

						JXLCreateResult jxCreateResult = new JXLCreateResult(filePath,baseInfo,observeInfosA0,
								correctDataInfoLists,OutputProUI.this);
						fixedThreadPool.execute(jxCreateResult);

						SharedPreferences sharedPreferences=getSharedPreferences("defaultFilePath",0);
						sharedPreferences.edit().putString("Path", filePath).commit();
						outputByProjectNameBtn.setEnabled(false);
					}
				}
				if(flag1==0){
					showMsg("导出失败！此工程中的所有孔都没有数据！");
				}else
					if(flag2==1){
						showMsg("导出成功！但此工程中存在没有数据的孔！");
					}
					else{
						showMsg("导出成功！");
					}
			}else
			{	// 弹出吐司，表示导出失败
				Toast.makeText(OutputProUI.this, "导出失败！",
						Toast.LENGTH_LONG).show();
			}
			}
		}
	};
	/**
	 * 导出一个项目中的一个工点的所有数据
	 */
	private OnClickListener outputByItemNameClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			/*
			 * 取出数据的过程： 1.通过两个参数选出唯一的钻孔编号的记录ID-base_id 2.通过base_id选出所有的观察记录的集合
			 * List<ObserveInfo> 3.解析观察记录集合，一个一个的将对应的文件输出（每个ob_id对应了一组数据，有可能为空）
			 */
			String filePath = file_edit.getText().toString().trim();
			if(projectNameSp.getSelectedItem()==null){
				showMsg("工程为空，导出失败！");
			}else{
			String _projectName = projectNameSp.getSelectedItem().toString();
			String _itemName = itemNameSp.getSelectedItem().toString();
			List<BaseInfo> all = baseInfoDao.selectBaseInfos(_projectName,_itemName);
			int flag1=0,flag2=0;           //标志flag1==0全部为空，flag2==1部分为空
			if(BaseUtil.isEmpty(filePath,OutputProUI.this)){
				for (BaseInfo baseInfo : all) {
					ObserveInfo observeInfo0 = new ObserveInfo();/***检验上一次的观测信息是否有对应的修正信息**/
					List<ObserveInfo> alls1= new ArrayList<ObserveInfo>();
				alls1= observeInfoDao.selectObserverInfos(baseInfo.getBaseId(),
						MEASURE_ANGLE_0);
				// 判断取出的记录是否为空
				if (alls1.size() < 1) {
					observeInfo0.setCount(1);
				} else {//
				int max1= 1;
				for (ObserveInfo observeInfo3 : alls1) {
					int i = observeInfo3.getCount();
					if (i > max1){
						max1= i;
					}
				 }

				ObserveInfo observeInfo1=observeInfoDao.selectObserveInfo(MEASURE_ANGLE_0,baseInfo.getBaseId(),max1);
				int obId=observeInfo1.getObserveId();
				int obId1=obId+1;
				List<CorrectDataInfo> correctDataInfos=correctDataInfoDao.selectDataInfos(obId);
				if (correctDataInfos.size()<=0) {
					observeInfoDao.deleteObserveInfoByobId(obId);
					observeInfoDao.deleteObserveInfoByobId(obId1);
					}else{


					}
		     }//*///
					List<ObserveInfo> observeInfos = observeInfoDao
							.selectObserverInfos(baseInfo.getBaseId());
					if (observeInfos.size() < 1) {
						flag2=1;
					} else {
						//导出单次观测的观测数据和修正数据
						flag1=1;
						for (ObserveInfo observeInfo : observeInfos) {
							//只根据A0方向的ob_id导出相应修正数据的文件，A180方向的观测信息无用
							//导出功能中，只导出A0，A180两个方向数据计算后的主滑、非主滑、合成滑动位移
							if(observeInfo.getMeasurecount().equals(MEASURE_ANGLE_0)){
								List<CorrectDataInfo> correctDataInfoList = correctDataInfoDao.
										selectDataInfos(observeInfo.getObserveId());
								if(observeInfo.getCount()==1){
									//如果是第一次观测，且有修正观测数据，设置三种位移值都为0
									if(correctDataInfoList.size()>0){
										for(CorrectDataInfo correctDataInfo:correctDataInfoList){
											correctDataInfo.setLx("0");
											correctDataInfo.setLy("0");
											correctDataInfo.setError("0");
										}
									}
								}
								JXLCreate jxCreate = new JXLCreate(filePath,baseInfo,observeInfo,correctDataInfoList,OutputProUI.this);
								new Thread(jxCreate).start();
							}
						}
						//导出多次观测的修正数据
						List<ObserveInfo> observeInfosA0 = observeInfoDao
								.selectObserverInfos(baseInfo.getBaseId(),MEASURE_ANGLE_0);
						List<List<CorrectDataInfo>> correctDataInfoLists =new ArrayList<List<CorrectDataInfo>>();
						//取出每一次观测的修正数据List
						for(ObserveInfo observeInfo:observeInfosA0){
							List<CorrectDataInfo> correctDataInfos=new ArrayList<CorrectDataInfo>();
							correctDataInfos=correctDataInfoDao.selectDataInfos(observeInfo.getObserveId());
							correctDataInfoLists.add(correctDataInfos);
						}

						JXLCreateResult jxCreateResult = new JXLCreateResult(filePath,baseInfo,observeInfosA0,
								correctDataInfoLists,OutputProUI.this);
						fixedThreadPool.execute(jxCreateResult);

						SharedPreferences sharedPreferences=getSharedPreferences("defaultFilePath",0);
						sharedPreferences.edit().putString("Path", filePath).commit();
						outputByItemNameBtn.setEnabled(false);
					}
				}
				if(flag1==0){
					showMsg("导出失败！此工点中的所有孔都没有数据！");
				}else
					if(flag2==1){
						showMsg("导出成功！但此工点中存在没有数据的孔！");
					}
					else{
						showMsg("导出成功！");
					}
			}else
			{	// 弹出吐司，表示导出失败
				Toast.makeText(OutputProUI.this, "导出失败！",
						Toast.LENGTH_LONG).show();
			}
			}
		}
	};
	/**
	 * 按钻孔导出按钮监听
	 */
	private OnClickListener outputByDrillClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			/*
			 * 取出数据的过程： 1.通过三个参数选出唯一的钻孔编号的记录ID-base_id 2.通过base_id选出所有的观察记录的集合
			 * List<ObserveInfo> 3.解析观察记录集合，一个一个的将对应的文件输出（每个ob_id对应了一组数据，有可能为空）
			 */
			String filePath = file_edit.getText().toString().trim();
			if(projectNameSp.getSelectedItem()==null){
				showMsg("工程为空，导出失败！");
			}else{
			String _projectName = projectNameSp.getSelectedItem().toString();
			String _itemName = itemNameSp.getSelectedItem().toString();
			String _drillNum = drillNumSp.getSelectedItem().toString();

			BaseInfo baseInfo = baseInfoDao.selectBaseInfos(_projectName,
					_itemName, _drillNum);
			ObserveInfo observeInfo0 = new ObserveInfo();/***检验上一次的观测信息是否有对应的修正信息**/
			List<ObserveInfo> alls1= new ArrayList<ObserveInfo>();
		alls1= observeInfoDao.selectObserverInfos(baseInfo.getBaseId(),
				MEASURE_ANGLE_0);
		// 判断取出的记录是否为空
		if (alls1.size() < 1) {
			observeInfo0.setCount(1);
		} else {//
		int max1= 1;
		for (ObserveInfo observeInfo3 : alls1) {
			int i = observeInfo3.getCount();
			if (i > max1){
				max1= i;
			}
		 }

		ObserveInfo observeInfo1=observeInfoDao.selectObserveInfo(MEASURE_ANGLE_0,baseInfo.getBaseId(),max1);
		int obId=observeInfo1.getObserveId();
		int obId1=obId+1;
		List<CorrectDataInfo> correctDataInfos=correctDataInfoDao.selectDataInfos(obId);
		if (correctDataInfos.size()<=0) {
			observeInfoDao.deleteObserveInfoByobId(obId);
			observeInfoDao.deleteObserveInfoByobId(obId1);
			}else{


			}
     }//*///

			List<ObserveInfo> observeInfos = observeInfoDao

					.selectObserverInfos(baseInfo.getBaseId());
			if(BaseUtil.isEmpty(filePath,OutputProUI.this)){
				if (observeInfos.size() < 1) {
					showMsg("导出失败！此孔没有数据！");
				} else {
					//导出单次观测的观测数据和修正数据
					for (ObserveInfo observeInfo : observeInfos) {
						//只根据A0方向的ob_id导出相应修正数据的文件，A180方向的观测信息无用
						//导出功能中，只导出A0，A180两个方向数据计算后的主滑、非主滑、合成滑动位移
						if(observeInfo.getMeasurecount().equals(MEASURE_ANGLE_0)){
							List<CorrectDataInfo> correctDataInfoList = correctDataInfoDao.
									selectDataInfos(observeInfo.getObserveId());
							if(observeInfo.getCount()==1){
								//如果是第一次观测，且有修正观测数据，设置三种位移值都为0
								if(correctDataInfoList.size()>0){
									for(CorrectDataInfo correctDataInfo:correctDataInfoList){
										correctDataInfo.setLx("0");
										correctDataInfo.setLy("0");
										correctDataInfo.setError("0");
									}
								}
							}
							JXLCreate jxCreate = new JXLCreate(filePath,baseInfo,observeInfo,correctDataInfoList,OutputProUI.this);
							new Thread(jxCreate).start();
							outputByDrillNumBtn.setEnabled(false);
							showMsg("导出成功！");
						}
					}
					//导出多次观测的修正数据
					List<ObserveInfo> observeInfosA0 = observeInfoDao
							.selectObserverInfos(baseInfo.getBaseId(),MEASURE_ANGLE_0);
					List<List<CorrectDataInfo>> correctDataInfoLists =new ArrayList<List<CorrectDataInfo>>();
					//取出每一次观测的修正数据List
					for(ObserveInfo observeInfo:observeInfosA0){
						List<CorrectDataInfo> correctDataInfos=new ArrayList<CorrectDataInfo>();
						correctDataInfos=correctDataInfoDao.selectDataInfos(observeInfo.getObserveId());
						correctDataInfoLists.add(correctDataInfos);
					}

					JXLCreateResult jxCreateResult = new JXLCreateResult(filePath,baseInfo,observeInfosA0,
							correctDataInfoLists,OutputProUI.this);
					fixedThreadPool.execute(jxCreateResult);

					SharedPreferences sharedPreferences=getSharedPreferences("defaultFilePath",0);
					sharedPreferences.edit().putString("Path", filePath).commit();
				}
			}else
			{	// 弹出吐司，表示导出失败
				Toast.makeText(OutputProUI.this, "导出失败！",
						Toast.LENGTH_LONG).show();
			}
			}
		}
	};
	/**
	 * 导出备份
	 */
	private OnClickListener exportBackupClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			String filePath = export_backup_edit.getText().toString().trim();
			List<BaseInfo> all = baseInfoDao.selectBaseInfos();
			if(BaseUtil.isEmpty(filePath,OutputProUI.this)){
				if(all.size()<1){
					showMsg("工程为空，导出失败！");
				}else{
					for (BaseInfo baseInfo : all) {
						ObserveInfo observeInfo0 = new ObserveInfo();/***检验上一次的观测信息是否有对应的修正信息**/
							List<ObserveInfo> alls1= new ArrayList<ObserveInfo>();//
						alls1= observeInfoDao.selectObserverInfos(baseInfo.getBaseId(),
								MEASURE_ANGLE_0);
						// 判断取出的记录是否为空
						if (alls1.size() < 1) {
							observeInfo0.setCount(1);
						} else {//
							int max1= 1;
							for (ObserveInfo observeInfo3 : alls1) {
								int i = observeInfo3.getCount();
								if (i > max1){
									max1= i;
								}
							 }
							//删除没有修正记录的观测数据
							ObserveInfo observeInfo1=observeInfoDao.selectObserveInfo(MEASURE_ANGLE_0,baseInfo.getBaseId(),max1);
							int obId=observeInfo1.getObserveId();
							int obId1=obId+1;
							List<CorrectDataInfo> correctDataInfos=correctDataInfoDao.selectDataInfos(obId);
							if (correctDataInfos.size()<=0) {
								observeInfoDao.deleteObserveInfoByobId(obId);
								observeInfoDao.deleteObserveInfoByobId(obId1);
								}else{

								}
						}
						List<ObserveInfo> observeInfos = observeInfoDao
								.selectObserverInfos(baseInfo.getBaseId());
						if (observeInfos.size() >= 1) {

							List<List<BaseInfo>> baseInfoLists = new ArrayList<List<BaseInfo>>();
							List<BaseInfo> baseInfoList = new ArrayList<BaseInfo>();
							baseInfoList=baseInfoDao.selectBaseInfos();
							baseInfoLists.add(baseInfoList);

							List<List<ObserveInfo>> observeInfoLists= new ArrayList<List<ObserveInfo>>();
							List<ObserveInfo> observeInfoList= new ArrayList<ObserveInfo>();
							observeInfoList=observeInfoDao.selectObserverInfos();
							observeInfoLists.add(observeInfoList);

							List<List<DataInfo>> dataInfoLists=new ArrayList<List<DataInfo>>();
							List<DataInfo> dataInfoList=new ArrayList<DataInfo>();
							dataInfoList=dataInfoDao.selectDataInfos();
							dataInfoLists.add(dataInfoList);

							List<List<RealInfo>> realInfoLists=new ArrayList<List<RealInfo>>();
							List<RealInfo> realInfoList=new ArrayList<RealInfo>();
							realInfoList=realInfoDao.selectRealInfos();
							realInfoLists.add(realInfoList);

							List<List<LeijiInfo>> leijiInfoLists=new ArrayList<List<LeijiInfo>>();
							List<LeijiInfo> leijiInfoList=new ArrayList<LeijiInfo>();
							leijiInfoList=leijiInfoDao.selectLjDataInfos();
							leijiInfoLists.add(leijiInfoList);

							List<List<CorrectDataInfo>> correctDataInfoLists1 =new ArrayList<List<CorrectDataInfo>>();
							List<CorrectDataInfo> correctDataInfos1=new ArrayList<CorrectDataInfo>();
							correctDataInfos1=correctDataInfoDao.selectDataInfos();
							correctDataInfoLists1.add(correctDataInfos1);

							JXLExportAll jxExportAll = new JXLExportAll(filePath, baseInfo,correctDataInfoLists1,dataInfoLists,leijiInfoLists,observeInfoLists,baseInfoLists,realInfoLists,OutputProUI.this);
							fixedThreadPool.execute(jxExportAll);
							SharedPreferences sharedPreferences=getSharedPreferences("defaultFilePath",0);
							sharedPreferences.edit().putString("ExportBackupPath", filePath).commit();
						}
					}
					exportBackupBtn.setEnabled(false);
					showMsg("导出成功！");
				}
			}else{
				Toast.makeText(OutputProUI.this, "导出失败！",
						Toast.LENGTH_LONG).show();
			}
		}
	};
	/**
	 * 导入备份
	 */
	private OnClickListener importBackupClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			String filePath = import_backup_edit.getText().toString().trim();
			File file=new File(filePath);
			String filename = file.getName();
		//	String str=filename.substring(0,filename.lastIndexOf("."));

			if(filePath==null||"".equals(filePath)){
				showMsg("导入文件路径不能为空！");
			}else{
				if(!file.exists()){
					showMsg("该文件不存在！");
				}else{
					if(!filename.endsWith(".xls")){
						showMsg("请选择或输入以.xls为后缀的文件！");
					}else{
						String str=filename.substring(0,filename.lastIndexOf("."));
						if(!isCorrectFormat(str)){
							showMsg("请选择或输入正确格式的备份文件！");
						}else{
							List<BaseInfo> baseInfoList=JXLImportAll.loadBaseInfo(filePath);
							List<ObserveInfo> observeInfoList=JXLImportAll.loadObserveInfo(filePath);
							List<DataInfo> dataInfoList=JXLImportAll.loadDataInfo(filePath);
							List<LeijiInfo> leijidataInfoList=JXLImportAll.loadLeijiInfo(filePath);
							List<CorrectDataInfo> correctDataInfoList=JXLImportAll.loadCorrectDataInfo(filePath);
							List<RealInfo> realInfoList=JXLImportAll.loadRealInfo(filePath);

							boolean flag=baseInfoDao.insertList(baseInfoList,observeInfoList,dataInfoList,leijidataInfoList,correctDataInfoList,realInfoList);
							if(flag){
								importBackupBtn.setEnabled(false);
								showMsg("导入成功！");
							}else{
								showMsg("导入失败！");
							}
						}
					}
				}
			}
		}
	};
	/**
	 * 判断导入备份文件，文件名的格式符不符合条件
	 * @param str
	 * @return
	 */
	public static boolean isCorrectFormat(String str) {
	    // TODO Auto-generated method stub
	    Pattern pattern = Pattern.compile("[0-9][0-9][0-9][0-9]" + "-" + "[0-9][0-9]" + "-" + "[0-9][0-9]" + " " + "[0-9][0-9]"+ "_" + "[0-9][0-9]" + "_" + "[0-9][0-9]"+"-备份");
	    Matcher isNum = pattern.matcher(str);
	    if(!isNum.matches())
	    {
	        return false;
	    }
	    return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(FILE_RESULT_CODE == requestCode){
			Bundle bundle = null;
			if(data!=null&&(bundle=data.getExtras())!=null){
				file_edit.setText(bundle.getString("file"));
			}
			FILE_RESULT_CODE=0;
		}
		if(FILE_EXPORT_CODE == requestCode){
			Bundle bundle = null;
			if(data!=null&&(bundle=data.getExtras())!=null){
				export_backup_edit.setText(bundle.getString("file"));
			}
			FILE_EXPORT_CODE=0;
		}
		if(FILE_IMPORT_CODE == requestCode){
			Bundle bundle = null;
			if(data!=null&&(bundle=data.getExtras())!=null){
				import_backup_edit.setText(bundle.getString("file"));
			}
			FILE_IMPORT_CODE=0;
		}
	}

	private void showMsg(String msg) {
		Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			sureDialog();
			return true;
		}
		return true;
	}

	/**
	 * 确认框
	 */
	public void sureDialog() {
		AlertDialog.Builder builder = new Builder(this);
		builder.setMessage("确定退出程序吗？");
		builder.setTitle("提示");
		builder.setPositiveButton("确定",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						// AccoutList.this.finish();
						// System.exit(1);
						android.os.Process.killProcess(android.os.Process
								.myPid());
					}
				});
		builder.setNegativeButton("取消",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		builder.create().show();
	}

	/**
	 * 初始化三级联动菜单
	 */
	private void initMenu() {
		try {
			initMenu1();
			initMenu2();
			initMenu3();
		} catch (Exception e) {

		}
	}

	private void initMenu1() throws Exception {
		// ---------------------初始化项目名称-start---------------------------
		Set<String> projectNameSet = new HashSet<String>(); // 保存不重复的项目名
		List<String> projectNames = new ArrayList<String>(); // 将Set集合转成List集合,从而放入适配器

		List<BaseInfo> allBaseInfo = this.baseInfoDao.selectBaseInfos();

		for (BaseInfo baseInfo : allBaseInfo) {
			projectNameSet.add(baseInfo.getProjectName());
		}
		for (String projectName : projectNameSet) {
			projectNames.add(projectName);
		}
		Collections.sort(projectNames);//顺序排列
		// 把数组导入到ArrayList中
		projectAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, projectNames);
		projectAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// 设置下拉菜单的风格
		projectNameSp.setAdapter(projectAdapter);
		// 绑定适配器
		projectNameSp.setPrompt("请选择项目名");
	}

	private void initMenu2() throws Exception {
		// **************************初始化二级联动菜单**start****************************
		String selectedProject = projectNameSp.getSelectedItem().toString();
		Set<String> allItemsSet = new HashSet<String>();
		List<String> allItemsList = new ArrayList<String>();
		List<BaseInfo> allItems = this.baseInfoDao
				.selectBaseInfos(selectedProject); // 通过选中的项目名来取得对应的记录，从而得出二级目录的数据
		for (BaseInfo baseInfo : allItems) {
			allItemsSet.add(baseInfo.getItemName());
		}
		for (String item : allItemsSet) {
			allItemsList.add(item);
		}
		Collections.sort(allItemsList);//顺序排列
		// 把数组导入到ArrayList中
		itemAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, allItemsList);
		itemAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// 设置下拉菜单的风格
		itemNameSp.setAdapter(itemAdapter);
		// 绑定适配器
		itemNameSp.setPrompt("请选择工点名");
		// **************************初始化二级联动菜单**end*************************
	}

	private void initMenu3() throws Exception {
		String selectedProject = projectNameSp.getSelectedItem().toString();
		String selectedItem = itemNameSp.getSelectedItem().toString();
		Set<String> allDrillSet = new HashSet<String>();
		List<String> allDrillList = new ArrayList<String>();

		List<BaseInfo> allDrills = this.baseInfoDao.selectBaseInfos(
				selectedProject, selectedItem);
		for (BaseInfo baseInfo : allDrills) {
			allDrillSet.add(baseInfo.getDrillNum());
		}
		for (String drillNum : allDrillSet) {
			allDrillList.add(drillNum);
		}
		Collections.sort(allDrillList);//顺序排列
		drillAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, allDrillList);
		drillAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		drillNumSp.setAdapter(drillAdapter);
		drillNumSp.setPrompt("请选择钻孔编号");
	}

	private String getSDPath(Context context) {
		String sdDir = null;
		boolean sdCardExist = Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
		if (sdCardExist) {
			sdDir = Environment.getExternalStorageDirectory().getAbsolutePath();// 获取根目录
		} else {// 提示没检测到SD卡
			Toast.makeText(context, "没检测到SD卡！", Toast.LENGTH_SHORT).show();
		}
		return sdDir;
	}

	/**
	 * 点击空白处时，隐藏键盘
	 *
	 *
	 */
	@Override
    public boolean onTouchEvent(MotionEvent event){
        if(event.getAction()==MotionEvent.ACTION_DOWN){
            if(OutputProUI.this.getCurrentFocus() != null && OutputProUI.this.getCurrentFocus().getWindowToken() != null){
                    inputMethodManager.hideSoftInputFromWindow(OutputProUI.this.getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
        return super.onTouchEvent(event);
    }

}

